package com.bw.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.home.intent.SimpleVideoIntent
import com.bw.home.service.SimpleVideoService
import com.bw.home.state.SimpleVideoState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class SimpleVideoViewModel : BaseViewModel<SimpleVideoIntent>() {
    private val service: SimpleVideoService by lazy { SimpleVideoService() }
    private val _state = MutableStateFlow<SimpleVideoState>(SimpleVideoState.init)
    val state: StateFlow<SimpleVideoState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is SimpleVideoIntent.getSimpleVideoIntent -> {
                        doSimpleVideo(it)
                    }

                    is SimpleVideoIntent.getRecommendVideoIntent->{
                        doRecommendVideo(it)
                    }

                    else -> {}
                }
            }
        }
    }

    private fun doRecommendVideo(it: SimpleVideoIntent.getRecommendVideoIntent) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getRecommendVideo(it.page, it.pageSize)
            if(data.code==0){
                _state.value = SimpleVideoState.getRecommendVideoState(data.data)
            } else {
                _state.value = SimpleVideoState.Failed
            }
        }
    }

    private fun doSimpleVideo(it: SimpleVideoIntent.getSimpleVideoIntent) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getSimpleVideo(it.channelId, it.page, it.pageSize)
            if (data.code == 0) {
                _state.value = SimpleVideoState.getSimpleVideoState(data.data)
            } else {
                _state.value = SimpleVideoState.Failed
            }
        }
    }
}





